﻿using System;
using System.Collections.Generic;
using QFramework;

namespace Gp.Scripts.Core
{
    public class EventHandler
    {
        private List<IUnRegister> _unRegisters;

        public IUnRegister RegisterEvent<T>(Action<T> callBack)
        {
            _unRegisters ??= new List<IUnRegister>();
            var unRegister = MainArchitecture.Interface.RegisterEvent(callBack);
            _unRegisters.Add(unRegister);
            return unRegister;
        }


        public void UnRegisterEvent<T>(Action<T> callBack)
        {
            MainArchitecture.Interface.UnRegisterEvent(callBack);
        }


        public IUnRegister DoSchedule(float interval, ScheduleDelegate action)
        {
            _unRegisters ??= new List<IUnRegister>();
            var unRegister = Global.Get<ScheduleManager>().RegisterSchedule(interval, action);
            _unRegisters.Add(unRegister);
            return unRegister;
        }

        public void StopAllSchedule()
        {
            if (_unRegisters == null) return;
            
            for (var i = _unRegisters.Count - 1; i >= 0; i--)
            {
                if (_unRegisters[i] is not ScheduleUnRegister scheduleUnRegister) continue;
                scheduleUnRegister.UnRegister();
                _unRegisters.RemoveAt(i);
            }
        }


        public void UnRegisterAll()
        {
            _unRegisters?.ForEach(x => x.UnRegister());
        }
    }
}